﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.BusinessModel.DAL;
using iLangl.Model;

namespace iLangl.BusinessModel.Managers
{
	public class PluginManager
	{
		#region Singelton Pattern
		private PluginManager()
		{
		}

		private static PluginManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the PluginManager.
		/// </summary>
		public static PluginManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new PluginManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public PluginData GetPlugin(String pluginId)
		{
			return DALFacade.Instance.PluginDAL.ReadPlugin(pluginId);
		}

		public void RegisterPlugin(PluginData plugin)
		{
			DALFacade.Instance.PluginDAL.RegisterPlugin(plugin, null);
		}

		public PluginLicense GetLicense(String licenseKey)
		{
			return DALFacade.Instance.PluginDAL.ReadLicense(licenseKey);
		}

		public PluginLicense GetLicenseByUserAccountId(String userAccountId)
		{
			return DALFacade.Instance.PluginDAL.ReadLicenseByUserAcount(userAccountId);
		}

		public PluginLicense GetLicenseByCompanyId(String companyid)
		{
			return DALFacade.Instance.PluginDAL.ReadLicenseByCompanyId(companyid);
		}

		public String RegisterNewPluginUser(PluginRegistration plugRegistration)
		{
			//Define UserId
			string userId = Facade.Instance.AuthenticationService.GetUserId(plugRegistration.SessionId);

			//Register Company
			CompanyManager.Instance.CreateCompany(plugRegistration.Company, plugRegistration.PrimaryContactId, userId);

			PluginData pluginData = PluginManager.Instance.GetPlugin(plugRegistration.PluginId);

			if (pluginData == null)
			{
				throw new ApplicationException(String.Format("Requested plugin '{0}' with Id= {1}  and Version= {2} is not supported!", plugRegistration.PluginName, plugRegistration.PluginId, plugRegistration.PluginVersion));
			}

			if(pluginData.IsTranslationProvider)
				TranslationProviderManager.Instance.RegisterTranslationProvider(plugRegistration.Company);

			String pluginLicence = DALFacade.Instance.PluginDAL.CreatePluginLicense(plugRegistration, userId, null);

			PluginLicense license = GetLicense(pluginLicence);
			CompanyManager.Instance.AddSubscriber(plugRegistration.Company, license, false);

			return pluginLicence;
		}

		
	}
}
